<template>
  <div
    class="logincontend"
    :style="{ backgroundImage: `url(${loginBg})` }"
    v-loading="loading"
    :element-loading-text="loadingText"
  >
    <el-row :gutter="120" justify="end">
      <el-col :xs="24" :sm="24" :md="12" :lg="16">
        <div style="margin-left: 5%">
          <h1 class="login-title">深圳市集中隔离风险管理系统</h1>
          <!-- <div>
            <el-link>
              <h3>智慧物业</h3>
            </el-link>
            <el-divider direction="vertical"></el-divider>
            <el-link>
              <h3>智慧租赁</h3>
            </el-link>
            <el-divider direction="vertical"></el-divider>
            <el-link>
              <h3>项目管理</h3>
            </el-link>
            <el-divider direction="vertical"></el-divider>
            <el-link>
              <h3>授权考核</h3>
            </el-link>
            <el-link type="primary" style="margin-left: 20px">
              <h2>智慧物业管理，提升价值共识</h2>
            </el-link>
          </div>-->
        </div>
      </el-col>
      <el-col :xs="24" :sm="24" :md="12" :lg="8">
        <el-card v-if="!isLogin" shadow="never" class="login-box">
          <div class="logoimg">
            <!-- <div class="name">深圳市集中隔离风险管理系统</div> -->
          </div>
          <!--   <el-divider /> -->
          <div class="tab-wrapper">
            <el-tabs v-model="activeName">
              <el-tab-pane label="账号密码登录" name="first">
                <el-form
                  class="form-wrapper"
                  ref="loginForm"
                  :model="loginForm"
                  :rules="rules"
                >
                  <el-form-item prop="username">
                    <div class="input-zh-icon"></div>
                    <el-input
                      v-halfCharCode
                      type="text"
                      clearable
                      placeholder="请输入账号"
                      v-model.trim="loginForm.username"
                    />
                    <!-- prefix-icon="el-icon-user" -->
                  </el-form-item>
                  <el-form-item prop="password">
                    <div class="input-mm-icon"></div>
                    <el-input
                      v-halfCharCode
                      type="password"
                      clearable
                      placeholder="请输入密码"
                      v-model.trim="loginForm.password"
                    />
                    <!-- prefix-icon="el-icon-unlock" -->
                    <i class="iconfont icon-mima"></i>
                  </el-form-item>
                  <el-form-item prop="code">
                    <div class="input-yzm-icon"></div>
                    <el-input
                      v-halfCharCode
                      placeholder="请输入验证码"
                      v-model="loginForm.code"
                      @keyup.enter.native="onSubmit('loginForm')"
                    >
                      <!-- prefix-icon="el-icon-key" -->
                      <template slot="append">
                        <img :src="codeUrl" @click="getCode" />
                      </template>
                    </el-input>
                    <i class="iconfont icon-yanzhengma"></i>
                  </el-form-item>
                  <el-form-item style="height: 30px"></el-form-item>
                  <el-form-item>
                    <el-button
                      size="medium"
                      type="primary"
                      v-on:click="onSubmit('loginForm')"
                      class="login-primary-btn"
                      >登录</el-button
                    >
                    <!-- style="width: 100%;font-size:21px;background: #409EFF" -->
                  </el-form-item>
                </el-form>
              </el-tab-pane>

              <el-tab-pane label="手机号码登录" name="second">
                <el-form
                  class="form-wrapper"
                  ref="mobileLoginForm"
                  :model="mobileLoginForm"
                  :rules="mobileLoginFormRules"
                >
                  <el-form-item prop="telnumber">
                    <div class="input-zh-icon"></div>
                    <el-input
                      v-halfCharCode
                      type="text"
                      clearable
                      placeholder="请输入手机号"
                      v-model="mobileLoginForm.telnumber"
                    />
                    <!-- prefix-icon="el-icon-user" -->
                  </el-form-item>
                  <el-form-item prop="password">
                    <div class="input-mm-icon"></div>
                    <el-input
                      v-halfCharCode
                      type="password"
                      clearable
                      placeholder="请输入密码"
                      v-model="mobileLoginForm.password"
                    />
                    <!-- prefix-icon="el-icon-unlock" -->
                  </el-form-item>
                  <el-form-item>
                    <!--滑块验证-->
                    <!--给子组件传数据，以及接受子组件改变后的数据-->
                    <slider
                      ref="slider"
                      v-bind:show="show"
                      v-on:showChange="zdy($event)"
                    ></slider>
                  </el-form-item>
                  <!--此为滑块控制的输入手机验证码部分-->
                  <el-form-item prop="telcode" v-if="show">
                    <el-input
                      v-halfCharCode
                      size="medium"
                      clearable
                      placeholder="请输入手机验证码"
                      v-model="mobileLoginForm.telcode"
                      class="input-with-select"
                    >
                      <el-button
                        size="mini"
                        slot="append"
                        @click="phoneCode()"
                        style="background:#409EFF;color:#fff"
                        >获取验证码</el-button
                      >
                    </el-input>
                  </el-form-item>
                  <el-form-item style="height: 30px"></el-form-item>
                  <el-form-item>
                    <el-button
                      size="medium"
                      type="primary"
                      @click="PhoneOnSubmit('mobileLoginForm')"
                      class="login-primary-btn"
                      >登录</el-button
                    >
                    <!-- style="width: 100%;background: #409EFF" -->
                  </el-form-item>
                </el-form>
              </el-tab-pane>
            </el-tabs>

            <div class="wechat">
              <div
                class="wechat-img"
                :style="{ backgroundImage: `url(${wechatImg})` }"
              ></div>
              <p>移动端工作二维码</p>
            </div>
          </div>
        </el-card>
        <div v-else shadow="never" class="login-box">
          <div style="color: #fff;" class="login-content">
            <div class="el-header">
              <h3>欢迎您，{{ realName }}！</h3>
              <p>请选择隔离点进入系统</p>
            </div>
            <div class="el-main">
              <li
                v-for="i in isolations"
                :key="i.id"
                @click="selectedIsolation(i)"
                :title="i.name"
              >
                {{ i.name }}
              </li>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import dbl from "@/utils/dbl";
import { encrypt } from "@/utils/rsaEncrypt";
import { watermark } from "@/utils/extract";
import { fetchAllList } from "~/admin/api/dict";
import {
  login,
  getMenu,
  getCodeImg,
  getPhoneCodeImg,
  Phonelogin,
  setIsolation,
  getIsolations,
} from "@/api/login";
import slider from "@/views/wy-login/components/slider.vue";
const loginBg = require("@/assets/images/login-top-bg.png");
const wechatImg = require("@/assets/images/wechat.png");

import Cookies from "js-cookie";
import { removeWatermark } from "@/utils/extract";

export default {
  name: "Login",
  components: {
    slider,
  },
  data() {
    return {
      realName: "",
      isLogin: false,
      isolations: [],
      loginData: {},
      pwFlag: false,

      loginBg,
      wechatImg,
      loading: false,
      loadingText: "正在加载验证码",
      redirect: undefined,
      // 电话验证码
      show: false,
      // 标签页
      activeName: "first",
      //校验码图片地址
      codeUrl: "",
      // 表单
      loginForm: {
        username: "",
        telnumber: "",
        password: "",
        telcode: "",
        code: "",
        uuid: "",
      },
      // 手机登陆表单
      mobileLoginForm: {
        telnumber: process.env.NODE_ENV === "development" ? "17034642999" : "",
        password: process.env.NODE_ENV === "development" ? "123zxc!@" : "",
        telcode: "",
        uuid: "",
      },
      // 表单验证，需要在 el-form-item 元素中增加 prop 属性
      rules: {
        username: [
          { required: true, message: "账号不可为空", trigger: "blur" },
        ],
        password: [
          { required: true, message: "密码不可为空", trigger: "blur" },
        ],
        code: [{ required: true, message: "验证码不可为空", trigger: "blur" }],
      },
      mobileLoginFormRules: {
        telnumber: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
        ],
        password: [
          { required: true, message: "密码不可为空", trigger: "blur" },
        ],
        telcode: [
          { required: true, message: "验证码不可为空", trigger: "blur" },
        ],
      },
    };
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  created() {
    this.getCode();
  },
  mounted() {
    removeWatermark("name1");
    removeWatermark("phone1");
    // removeWatermark('deptName1')
  },
  methods: {
    phoneCode() {
      if (
        this.mobileLoginForm.telnumber == null ||
        this.mobileLoginForm.telnumber == ""
      ) {
        this.$message.info("请输入手机号码");
        return;
      }
      getPhoneCodeImg(this.mobileLoginForm.telnumber).then((res) => {
        this.mobileLoginForm.telcode = res.data.data.code;
        this.mobileLoginForm.uuid = res.data.data.uuid;
      });
    },
    // 电话验证码
    zdy(e) {
      this.show = e;
    },
    onSubmit(formName = "loginForm") {
      // 为表单绑定验证功能
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.login();
        } else {
          this.dialogVisible = true;
          return false;
        }
      });
    },
    PhoneOnSubmit(formName = "mobileLoginForm") {
      // 为表单绑定验证功能
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.Phonelogin();
        } else {
          this.dialogVisible = true;
          return false;
        }
      });
    },
    getCode() {
      this.loading = true;
      this.loadingText = "正在加载验证码";
      getCodeImg().then((res) => {
        this.loading = false;
        this.codeUrl = res.data.data.img;
        this.loginForm.uuid = res.data.data.uuid;
      });
    },
    Phonelogin() {
      this.loading = true;
      this.loadingText = "登录中……";
      const user = {
        telnumber: this.mobileLoginForm.telnumber,
        password: this.mobileLoginForm.password,
        rememberMe: false,
        code: this.mobileLoginForm.telcode,
        uuid: this.mobileLoginForm.uuid,
      };
      var pwFlag = false; //false:密码满足复杂度要求 true：密码不满足复杂度要求，需要修改
      var pwdRegex = new RegExp(
        "(?=.*\\d)(?=.*[a-zA-Z])(?=.*[!@#$%^&*()]).{8,15}"
      );
      if (!pwdRegex.test(user.password)) {
        pwFlag = true;
      }
      if (user.password !== this.cookiePass) {
        user.password = encrypt(user.password);
      }
      Phonelogin(user.telnumber, user.password, user.code, user.uuid)
        .then((resp) => {
          let data = resp.data.data;
          let token = data.token;
          let roles = data.user.roles;
          let userInfo = data.user.user;
          userInfo.deptId = data.user.deptId;
          userInfo.deptName = data.user.deptName;
          userInfo.deptCascadeCode = data.user.deptCascadeCode;
          userInfo.roleIdList = data.user.roleIdList;

          this.$store.commit("SET_USER", userInfo);
          this.$store.commit("SET_ROLES", roles);

          dbl.set("token", token);
          Cookies.set("dbl-user", JSON.stringify(userInfo), { expires: 30 });
          dbl.set("roles", roles);
          dbl.set("user", userInfo);
          if (pwFlag) {
            this.$message({
              message: "密码复杂度不够，请修改密码！",
              type: "warning",
            });
            // alert("密码复杂度不够，请先修改密码！");
            // this.$router.push(
            //   "/editPassword?userId=" +
            //   userInfo.userId +
            //   "&username=" +
            //   user.username
            // );
          } else {
            this.getDictData();
            this.$store.dispatch("init");
          }
        })
        .catch(() => {
          this.loading = false;
          this.getCode();
        });
    },
    login() {
      const user = {
        username: this.loginForm.username,
        password: this.loginForm.password,
        rememberMe: false,
        code: this.loginForm.code,
        uuid: this.loginForm.uuid,
      };
      this.pwFlag = false; //false:密码满足复杂度要求 true：密码不满足复杂度要求，需要修改
      var pwdRegex = new RegExp(
        "(?=.*\\d)(?=.*[a-zA-Z])(?=.*[!@#$%^&*()]).{8,15}"
      );
      if (!pwdRegex.test(user.password)) {
        this.pwFlag = true;
      }
      if (user.password !== this.cookiePass) {
        user.password = encrypt(user.password);
      }
      this.loading = true;
      this.loadingText = "登录中……";
      login(user.username, user.password, user.code, user.uuid)
        .then((resp) => {
          this.loginData = resp.data.data;
          this.realName = this.loginData.user.user.realName;

          this.doLogin();

          if (this.pwFlag) {
            this.$message({
              message: "密码复杂度不够，请修改密码！",
              type: "warning",
            });
            // alert("密码复杂度不够，请修改密码！");
            // this.$router.push(
            //   "/editPassword?userId=" + user.uuid + "&username=" + user.username
            // );
          }

          this.showIsolations(this.loginData.user.user.userId);
        })
        .catch(() => {
          this.loading = false;
          this.getCode();
        });
    },
    doLogin(isolation) {
      let data = this.loginData;

      let token = data.token;
      let roles = data.user.roles;
      let userInfo = data.user.user;
      userInfo.deptId = data.user.deptId;
      userInfo.deptName = data.user.deptName;
      userInfo.deptCascadeCode = data.user.deptCascadeCode;
      userInfo.roleCode = data.roleCode.map((i) => i.roleCode);
      userInfo.roleIdList = data.user.roleIdList;
      if (isolation) {
        userInfo.isolationId = isolation.id;
        userInfo.isolationName = isolation.name;
      }
      userInfo.isolations = this.isolations;
      //判断用户是否是初始密码，是的话提示跳转修改密码页
      this.$store.commit("SET_RESET_PASSWORD", data.orgFlag);
      dbl.set("needResetPassword", data.orgFlag);

      this.$store.commit("SET_USER", userInfo);
      this.$store.commit("SET_ROLES", roles);

      dbl.set("token", token);
      dbl.set("roles", roles);
      dbl.set("user", userInfo);
      Cookies.set("dbl-user", JSON.stringify(userInfo), { expires: 30 });
      Cookies.set("dbl-token", JSON.stringify(token), { expires: 30 });
    },
    getDictData() {
      fetchAllList().then((resp) => {
        let list = resp.data.data;
        dbl.set("dict", list);
        this.$store.state.dict = list;
        this.getUserMenu();
      });
    },
    // 显示隔离点
    showIsolations(userId) {
      this.loading = false;
      getIsolations(userId).then((res) => {
        console.log(3132, res);
        this.isolations = res.data.data;
        if (this.isolations.length == 0) {
          this.selectedIsolation();
        } else if (this.isolations.length == 1) {
          this.selectedIsolation(this.isolations[0]);
        } else {
          this.isLogin = true;
        }
      });
    },
    // 选择隔离点
    selectedIsolation(isolation) {
      this.doLogin(isolation);
      this.loading = true;
      if (isolation) {
        setIsolation(isolation).then((res) => {
          this.getDictData();
          this.$store.dispatch("init");
        });
      } else {
        this.getDictData();
        this.$store.dispatch("init");
      }
    },
    getUserMenu() {
      getMenu()
        .then((resp) => {
          this.loading = false;
          this.$message({
            showClose: true,
            message: "登录成功",
            type: "success",
            offset: 70,
          });

          let list = resp.data.data;
          dbl.set("menus", list);
          this.$store.commit("SET_MENU", list);
          let first = list[0];
          // 如果是掉线后登陆的话，判断缓存中是否有掉线前的地址，有的话就跳转过去
          let lastUrl = localStorage.getItem("lastUrl");
          if (lastUrl) {
            localStorage.removeItem("lastUrl");
            window.location.href = window.location.origin + lastUrl;
          } else {
            if (first.children && first.children.length > 0) {
              let second = first.children[0];
              if (second.children && second.children.length > 0) {
                //this.$router.replace({path: second.children[0].path})
                this.$router.replace({ path: "/risk" });
              } else {
                this.$router.replace({ path: second.path });
              }
            } else {
              this.$router.replace({ path: first.path });
            }
          }
        })
        .catch((err) => {
          this.err("菜单获取错误，请联系管理员");
        });
    },
  },
};
</script>

<style scoped lang="scss">
.logincontend {
  min-width: 100vw;
  position: absolute;
  width: 100%;
  height: calc(100vh) !important;
  top: 0;
  left: 0;
  bottom: 0;
  overflow-x: hidden;
  margin: 0px;
  padding: 0px;
  border-bottom: none;
  background-position: top;
  -webkit-background-size: contain;
  background-size: contain;
  background-repeat: no-repeat;
  font-family: SourceHanSansCN-Medium, SourceHanSansCN;

  .form-wrapper {
    margin-top: 50px;
    width: 100%;
    .iconfont {
      color: #ffffff;
      position: absolute;
      left: 0;
      bottom: 1px;
    }
  }

  .logoimg {
    margin-top: 268px;
    text-align: center;
    .name {
      font-size: 22px;
      font-weight: bold;
      color: #333;
    }

    img {
      width: 60%;
    }
  }

  .tab-wrapper {
    width: 343px;
    // height: 503px;
    background: #ffffff;
    padding: 25px 22px 43px 22px;
    box-sizing: border-box;
    box-shadow: 0px 0px 8px 0px rgba(0, 0, 0, 0.15);
    border-radius: 8px;
  }

  .input-zh-icon {
    position: absolute;
    top: 10px;
    left: 10px;
    width: 15px;
    height: 15px;
    background: url("img/zh-icon.png") no-repeat;
    background-size: contain;
  }
  .input-mm-icon {
    position: absolute;
    top: 10px;
    left: 10px;
    width: 15px;
    height: 15px;
    background: url("img/mm-icon.png") no-repeat;
    background-size: contain;
  }
  .input-yzm-icon {
    position: absolute;
    top: 10px;
    left: 10px;
    width: 15px;
    height: 15px;
    background: url("img/yzm-icon.png") no-repeat;
    background-size: contain;
  }

  .login-primary-btn {
    width: 100%;
    height: 42px;
    background: #ffac1e;
    border-radius: 24px !important;
    border-color: transparent;
  }

  .el-button--medium {
    padding: 12px 20px;
    font-size: 16px;
  }

  /deep/.el-button {
    border-radius: 0;
  }

  /deep/.el-tabs__nav-wrap::after {
    height: 0px;
  }

  /deep/.el-tabs__content {
    overflow: inherit;
  }

  /deep/.el-input-group__append,
  .el-input-group__prepend {
    border-left: 0;
    border-right: 0;
    border-top: 0;

    span {
      font-size: 12px !important;
    }
  }

  .el-divider--vertical {
    margin: 0px 16px;
  }

  .el-form {
    margin-top: 10%;

    /deep/.el-input__inner {
      border: 0px;
      // border-bottom: 1px solid #fffffc;
      border-bottom: 1px solid #cccccc;
    }
    /deep/ .el-input__inner::placeholder {
      color: #ccc;
      font-size: 13px;
    }
  }

  // h1,
  h3 {
    margin-bottom: 0rem;
    font-weight: 300;
  }

  h3 {
    /*margin-bottom: 1rem;*/
  }

  h1.login-title {
    color: #fff;
    font-size: 19px;
    // font-weight: bold;
    text-align: center;
    margin-top: 12%;
    margin-bottom: 1rem;
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    font-family: MicrosoftYaHei;
  }

  .el-divider {
    background: #f6f6f6;
  }

  .el-dialog__body {
    height: inherit !important;
  }

  .el-link.el-link--default {
    color: #fff;
  }
  .wechat {
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;
    margin: 29px auto;
    .wechat-img {
      width: 120px;
      height: 120px;
      padding: 2px;
      box-sizing: border-box;
      border-radius: 2px;
      border: 1px solid #d9dee2;
      background-size: cover;
    }
    p {
      color: #000000;
      margin-top: 10px;
      font-size: 13px;
      font-weight: 500;
    }
  }
}

.login-box {
  padding: 25px 16px;
  box-sizing: border-box;
  border-radius: 0;
  // height: 100vh;
  border: 0px;
  /deep/ .el-input-group__append {
    width: 81px;
    height: 21px;
    padding: 0;
    img {
      width: 100%;
      height: 100%;
    }
  }
  .login-content {
    padding-top: 180px;
    box-sizing: border-box;
    .el-header {
      text-align: center;
      h3 {
        font-size: 42px;
        margin-bottom: 20px;
        // font-weight: bold;
      }
      p {
        font-size: 24px;
      }
    }
    .el-main {
      margin: 20px auto;
      padding-bottom: 20px;
      box-sizing: border-box;
      background: #030b35;
      li {
        height: 60px;
        width: 100%;
        padding-left: 20px;
        padding-right: 10px;
        line-height: 60px;
        font-size: 24px;
        border-bottom: solid 1px rgb(105, 104, 104);
        cursor: pointer;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      li:hover {
        color: #319cff;
        text-shadow: 0px 0px 15px rgb(59, 165, 214);
      }
    }
  }
}
</style>
<style lang="scss">
.logincontend {
  .el-card,
  .login-box {
    // background-color: rgba(1, 11, 59, 0.7);
    background: transparent;
    .el-card__body {
      padding: 0;
    }
  }
  .el-tabs__item {
    // color: #fff;
    height: 20px;
    color: #666666;
    font-size: 15px;
    font-weight: 500;
  }
  .el-tabs__active-bar {
    height: 2px;
    background: #143892;
  }
  .el-tabs__nav {
    left: 50%;
    transform: translateX(-50%) !important;
  }
  .el-tabs__item.is-active {
    // color: #319cff;
    color: #143892;
  }
  .el-input__inner {
    // color: #fff;
    color: #000000;
    background-color: transparent;
    padding-left: 40px;
  }
  .el-form-item {
    margin-bottom: 10px;
  }
}

input:-webkit-autofill {
  -webkit-box-shadow: 0 0 0px 32px #03104d inset; /**通过边框阴影遮挡住背景*/
  -webkit-text-fill-color: #fff; /*自动填充内容的文本颜色*/
}
</style>
